package libs

import (
	"sync"
	"fmt"
	"time"
	"net/http"
	"config"
	"strings"
	"log"
)

type LockMap struct {
	Lock sync.RWMutex
	Data map[string]bool
}

func (lm *LockMap) Set(key string) {
	lm.Lock.RLock()
	if _, ok := lm.Data[key]; !ok {
		lm.Lock.RUnlock()
		lm.Lock.Lock()
		lm.Data[key] = true
		lm.Lock.Unlock()
	} else {
		lm.Lock.RUnlock()
	}
}

func (lm *LockMap) All() []string {
	data := make([]string, 0)
	lm.Lock.RLock()
	for k := range lm.Data {
		data = append(data, k)
	}
	lm.Lock.RUnlock()
	return data
}


// 钉钉机器人接口
func CallDingWebHook(title, text string) {
	body := fmt.Sprintf(
		`{
			"msgtype": "markdown",
			"markdown": {
				"title": "%s",
				"text": "%s"
			}
		}`, title, text+fmt.Sprintf("\n> ###### 来自 tigris %s", time.Now().Format("2006-01-02 15:04:05")))
	res, err := http.DefaultClient.Post(config.DingWebHook, "application/json", strings.NewReader(body))
	if err != nil {
		log.Print("Call ding web hook error: " + err.Error())
	} else if res.StatusCode != 200 {
		log.Printf("Call ding web hook isn't 200 is %d", res.StatusCode)
	}
}